using System;
using Framework.Timer;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace StateSystem.Loader
{
    public enum SceneName 
    {

        //初始化入口
        InitScene,
        //大厅页面
        LobbyScene,
        //游戏页面01，若多个游戏模式按需添加枚举
        GameScene
    }

    public class SceneLoader : ILoader
    {

        private readonly string         _targetScene;
        private          AsyncOperation _asyncLoader;
        private          Action         _onComplete;
        private          Action<float>  _onLoading;

        public SceneLoader(string targetScene) { this._targetScene = targetScene; }

        public SceneLoader(SceneName targetScene) { this._targetScene = targetScene.ToString(); }

        public void BeginLoad(Action<float> onLoading, Action onComplete)
        {
            this._onLoading                        = onLoading;
            this._onComplete                       = onComplete;
            this._asyncLoader                      = SceneManager.LoadSceneAsync(this._targetScene);
            this._asyncLoader.allowSceneActivation = false;
            GameUpdateMgr.Instance.AddUpdater(this.OnUpdate);
        }

        public void Active()
        {
            this._asyncLoader.completed            += OnLoaded;
            this._asyncLoader.allowSceneActivation =  true;
        }

        private void OnLoaded(AsyncOperation obj)
        {
            this._onComplete?.Invoke();
        }

        private void OnUpdate()
        {
            //Unity的异步加载在90%的时候会自动停止，除非开启自动跳转才会加载后续部分，因此在加载到90%时判断加载完成即可。
            if (this._asyncLoader.progress >= 0.9f)
            {
                this._onLoading?.Invoke(0.9f);
                GameUpdateMgr.Instance.RemoveUpdater(this.OnUpdate);
            }
            else
            {
                this._onLoading?.Invoke(this._asyncLoader.progress);
            }
        }

    }
}